package com.github.permissiondog.cancanpbackend.filter;

import com.github.permissiondog.cancanpbackend.model.Role;
import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AdminFilter", value = "/admin/*")
public class AdminFilter extends LoginFilter {
    @Override
    public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        if (!super.resolveUser(req, res)) {
            return;
        }
        User user = (User) req.getAttribute("user");
        if (!user.getRole().equals(Role.ADMIN)) {
            json(res, BaseResponse.builder().ok(false).msg("仅支持管理员操作").build());
            return;
        }
        super.doFilter(req, res, chain);
    }
}
